import { defineStore } from 'pinia';
import axios from 'axios';
import { fetchEventSource } from '@microsoft/fetch-event-source';

// 配置后端地址
const SERVER_IP = localStorage.getItem('server_ip');
// 提取公共的请求配置
const getRequestConfig = () => {
    const appKey = localStorage.getItem('chatWidgetAppKey');
    return {
        headers: {
            'Authorization': `Bearer ${appKey}`,
            'Content-Type': 'application/json',
            'Accept': '*/*'
        }
    };
};

export const useApiStore = defineStore('api', {
    state: () => ({
        modelList: [],
        loading: false,
        error: null,
        appKeyInfo: {
            select_model: '',
            system_model: '',
            api_get_num: {},
            token_get_num: 0
        },
        isSendingMessage: false,
        retryCount: 0,
        MAX_RETRIES: 3
    }),
    actions: {
        async getModelList() {
            this.loading = true;
            this.error = null;
            try {
                const response = await axios.get(SERVER_IP + '/llm/get_modellist', getRequestConfig());
                this.modelList = response.data;
            } catch (error) {
                this.error = error.response?.data || error.message;
                console.error('Failed to get model list:', this.error);
            } finally {
                this.loading = false;
            }
        },
        async getAppKeyInfo() {
            this.loading = true;
            this.error = null;
            try {
                const response = await axios.get(SERVER_IP + '/llm/get_appkey_info', getRequestConfig());
                this.appKeyInfo = response.data;
            } catch (error) {
                this.error = error.response?.data || error.message;
                console.error('Failed to get app key info:', this.error);
            } finally {
                this.loading = false;
            }
        },
        async setAppKeyInfo(select_model, system_model) {
            this.loading = true;
            this.error = null;
            try {
                const response = await axios.post(SERVER_IP + '/llm/set_appkey_info', {
                    select_model,
                    system_model
                }, getRequestConfig());
                return response.data;
            } catch (error) {
                this.error = error.response?.data || error.message;
                console.error('Failed to set app key info:', this.error);
                throw error;
            } finally {
                this.loading = false;
            }
        },

        async sendChatHistoryMessage(message,ChatHistoryID) {
            const url = SERVER_IP + '/llm/new_chat_interaction';
            console.log(message,ChatHistoryID,111)
            this.loading = true;
            this.error = null;
            try {
                const response = await axios.post(url, {
                    model: message.model,
                    messages:message.messages,
                    ChatHistoryID,
                }, getRequestConfig());
                return response.data;
            } catch (error) {
                this.error = error.response?.data || error.message;
                console.error('Failed to set app key info:', this.error);
                throw error;
            } finally {
                this.loading = false;
            }
        },
        async sendChatMessage(message, updateChat) {
            if (this.isSendingMessage) {
                return;
            }
            this.isSendingMessage = true;
            this.retryCount = 0;
            const url = SERVER_IP + '/llm/chat_interaction';
            const headers = getRequestConfig().headers;
            const body = JSON.stringify({
              ...message
            });
            console.log('请求参数:', body);
            return new Promise((resolve, reject) => {
                let fullResponse = '';
                const fetchWithRetry = () => {
                    fetchEventSource(url, {
                        method: 'POST',
                        headers,
                        body,
                        onopen(response) {
                            if (response.ok && response.status === 200) {
                                console.log('Connection made');
                            } else {
                                reject(new Error(`Failed to connect to the server: ${response.statusText}`));
                            }
                        },
                        onmessage(event) {
                            try {
                                const data = JSON.parse(event.data);
                                const newResponsePart = data.response;
                                fullResponse += newResponsePart;
                                // 这里可以更细致地处理每次接收到的新数据片段
                                // 比如如果是增量更新聊天记录，可只传入新片段
                                updateChat(newResponsePart);
                            } catch (parseError) {
                                console.error('Failed to parse SSE data:', parseError);
                            }
                        },
                        onclose: function () {
                            this.isSendingMessage = false;
                            resolve(fullResponse);
                        }.bind(this),
                        onerror: function (error) {
                            console.error('Error from server:', error);
                            if (this.retryCount < this.MAX_RETRIES) {
                                this.retryCount++;
                                console.log(`Retrying request (attempt ${this.retryCount})...`);
                                setTimeout(fetchWithRetry, 1000);
                            } else {
                                this.isSendingMessage = false;
                                reject(new Error('达到最大重试次数，请求失败'));
                            }
                        }.bind(this)
                    });
                };
                fetchWithRetry();
            });
        }
    }
});